<template>
  <div>
   <van-list
     v-model="loading"
     :finished="finished"
     finished-text="没有更多了"
     @load="onLoad"
   >
    <!-- 单个商品的具体信息 -->
      <breadItem
        v-for="item in list"
        :key="item.id"
        :item="item"
        :totalPrice.sync="totalPrice"
        @onminus="onminus"
        @onplus="onplus"
      >
      </breadItem>
   </van-list>
  </div>
</template>

<script>
import breadItem from './bread-item'
import { getGoodsList } from '@/api/goods.js'
import { setItem } from '@/utils/localStorage.js'

export default {
  props: {
    totalPrice: {
      type: Number
    }
  },
  data () {
    return {
      value: 1,
      list: [],
      loading: false, // van-list组件的
      finished: false, // van-list组件的
      breadInfoArr: []
    }
  },
  components: { breadItem },

  methods: {
    async onLoad() {
      const { data } = await getGoodsList()
      this.list = data.filter(item => item.goodsType === '零食小吃') // 获取 零食小吃类商品的 信息
    },
    onminus (item) { // 减号触发
      item.goodsStock++
      if (this.breadInfoArr.some(items => items.id === item.id)) {
        for (let i = 0; i < this.breadInfoArr.length; i++) {
          if (this.breadInfoArr[i].id === item.id) {
            this.breadInfoArr[i] = item
            break
          }
        }
      }
      // console.log(this.breadInfoArr)
      setItem('breadInfoArr', this.breadInfoArr)
    },
    onplus (item) { // 加号触发 item为当前点击的商品的信息
      item.goodsStock--
      if (this.breadInfoArr.some(items => items.id === item.id)) {
        for (let i = 0; i < this.breadInfoArr.length; i++) {
          if (this.breadInfoArr[i].id === item.id) {
            this.breadInfoArr[i] = item
            break
          }
        }
      } else {
        this.breadInfoArr.push(item)
      }
      // console.log(this.breadInfoArr)
      setItem('breadInfoArr', this.breadInfoArr)
    }
  }
}
</script>

<style>
   .goods-card {
    margin: 0;
    background-color: red;
  }
 .breadImg{
   width:300px;
   height:200px;
   margin:0 auto
 }
</style>
